
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@WebServlet(name = "ServletDome",value="/ServletDome")
public class ServletDome extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //产生随机数的方法
        RandomNum(request,response);
    }
    public void RandomNum(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //设定宽和高
        int width = 100;
        int height = 40;
        //产生画布
        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        Graphics2D g2d = bufferedImage.createGraphics();
        Random r = new Random();
        //产生随机背景颜色
        g2d.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        g2d.fillRect(0,0,width,height);
        //接收随机验证码文字
        String captchaText = RandomText(4);//产生随机验证码文字
        //储存文字
        ServletContext context = this.getServletContext();
        context.setAttribute("captcha",captchaText);
        //字体格式
        g2d.setFont(new Font("微软雅黑",Font.BOLD,24));
        //字体颜色
        g2d.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        //写字
        g2d.drawString(captchaText,10,25);
        //设置响应头
        response.setContentType("image/png");
        //数据输出流
        OutputStream out = response.getOutputStream();
        //把图片以png形式响应给客户端
        ImageIO.write(bufferedImage,"png",out);
        out.close();
    }

    private String RandomText(int length) {
        String chaptcha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
        Random r = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            stringBuilder.append((chaptcha.charAt(r.nextInt(chaptcha.length()))));
        }
        return stringBuilder.toString();
    }

}
